// 定义state - 存储权限相关状态
const state = {
  username: "",
  isManager: localStorage.getItem("isManager") ? Number(localStorage.getItem("isManager")) : 2, // 从localStorage恢复，确保是数字类型
  permissions: [],
};

// 定义mutations - 修改状态的方法
const mutations = {
  // 设置用户名
  SET_USERNAME: (state, username) => {
    state.username = username; // 更新用户名
    localStorage.setItem("username", username); // 持久化到 localStorage
  },
  SET_IS_MANAGER: (state, isManager) => {
    // 确保转换为数字
    state.isManager = Number(isManager);
    console.log("mutations: SET_IS_MANAGER 被调用，值为:", state.isManager);
    // 保存到localStorage
    localStorage.setItem("isManager", state.isManager);
  },
  // 设置权限信息
  SET_PERMISSIONS: (state, permissions) => {
    state.permissions = permissions; // 更新权限信息
    localStorage.setItem("permissions", JSON.stringify(permissions)); // 持久化到 localStorage
  },
};

// 定义actions - 提交mutation的方法
const actions = {
  // 提交用户名到 mutations
  setUsername({ commit }, username) {
    commit("SET_USERNAME", username); // 调用 SET_USERNAME mutation
  },
  // 添加设置isManager的action
  setIsManager({ commit }, isManager) {
    commit("SET_IS_MANAGER", isManager);
  },
  // 提交权限信息到 mutations
  setPermissions({ commit, state }, permissions) {
    if (state.username === "admin") {
      // 如果用户名是 admin，放开所有权限
      commit("SET_PERMISSIONS", ["add_info", "edit_info", "delete_info", "view_info"]);
    } else {
      commit("SET_PERMISSIONS", permissions); // 否则设置为传入的权限
    }
  },
  // 初始化状态的action
  initState({ commit }) {
    // 从localStorage恢复状态
    const username = localStorage.getItem("username");
    const isManager = localStorage.getItem("isManager");
    const permissions = localStorage.getItem("permissions");

    if (username) commit("SET_USERNAME", username);
    if (isManager) commit("SET_IS_MANAGER", isManager);
    if (permissions) commit("SET_PERMISSIONS", JSON.parse(permissions));
  },
};

// 定义getters - 获取状态的计算属性
const getters = {
  // 获取用户名
  getUsername: (state) => {
    return state.username; // 返回用户名
  },
  // 新增获取isManager的getter
  getIsManager: (state) => state.isManager,
  // 修改isAdmin判断逻辑：使用isManager值为1判断
  isAdmin: (state) => {
    const result = Number(state.isManager) === 1;
    console.log("isAdmin检查 - isManager值:", state.isManager, "结果:", result);
    return result;
  },
  // 添加hasPermission getter
  hasPermission: (state) => (permission) => {
    // 如果用户是管理员(isManager为1)，自动拥有所有权限
    if (Number(state.isManager) === 1) {
      return true;
    }
    // 否则检查permissions数组中是否包含该权限
    return state.permissions.includes(permission);
  },
};

// 导出模块
export default {
  namespaced: true, // 启用命名空间
  state, // 状态
  mutations, // 修改状态的方法
  actions, // 提交 mutations 的方法
  getters, // 获取状态的计算属性
};
